#include "../source/server.hpp"
void HandleClose(Channel *channel) {
  channel->Remove();
  delete channel;
}
void HandleRead(Channel *channel) {
  int fd = channel->Fd();
  char buf[1024] = {0};
  int ret = recv(fd, buf, 1023, 0);
  if (ret <= 0) {
    return HandleClose(channel);
  }
  channel->EnableWrite();
  std::cout << buf << std::endl;
}
void HandleWrite(Channel *channel) {
  int fd = channel->Fd();
  const char *data = "我有一个大offer";
  int ret = send(fd, data, strlen(data), 0);
  if (ret < 0) {
    return HandleClose(channel);
  }
  channel->DisableWrite();  // 关闭写监控
}

void HandleError(Channel *channel) { return HandleClose(channel); }
void HandleEvent(Channel *channel) { std::cout << "有了一个事件" << std::endl; }
void Acceptor(EventLoop *loop, Channel *lst_channel) {
  int fd = lst_channel->Fd();
  int newfd = accept(fd, NULL, NULL);
  if (newfd < 0) {
    return;
  }
  Channel *channel = new Channel(loop, newfd);
  channel->SetReadCallback(std::bind(HandleRead, channel));
  channel->SetWriteCallback(std::bind(HandleWrite, channel));
  channel->SetCloseCallback(std::bind(HandleClose, channel));
  channel->SetErrorCallback(std::bind(HandleError, channel));
  channel->SetEventCallback(std::bind(HandleEvent, channel));
  channel->EnableRead();
}

int main() {
  // Poller poller;
  EventLoop loop;
  Socket lst_sock;
  lst_sock.CreateServer(8500);

  // 为监听套接字创建一个Channel进行事件的管理，以及事件的处理
  Channel channel(&loop, lst_sock.Fd());
  // 回调中获取新连接，为新连接常见channel并且添加监控
  channel.SetReadCallback(std::bind(Acceptor, &loop, &channel));
  channel.EnableRead();
  while (1) {
    loop.Start();

    // std::vector<Channel *> actives;
    // // 开始监控
    // poller.Poll(&actives);
    // for (auto &a : actives)
    // {
    //   a->HandleEvent();
    // }

    // int new_fd = lst_sock.Accept();
    // if (new_fd < 0) {
    //   continue;
    // }
    // Socket cli_sock(new_fd);
    // char buffer[1024] = {0};
    // int ret = cli_sock.Recv(buffer, 1023);

    // if (ret < 0) {
    //   cli_sock.Close();
    //   continue;
    // }
    // cli_sock.Send(buffer, ret);
    // cli_sock.Close();
  }

  lst_sock.Close();
  return 0;
}